<template>
	<view class="content">
		<image class="logo" :src="iconFilePath"></image>
		<view>
			<button @click="updateImage()" mode="aspectFill">选择图片显示</button>
		</view>
		<view>
			<image :src="downloadedImage" mode="widthFix" v-if="downloadedImage"></image>
			<button @click="downloadNetImage()">下载网络图片</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				iconFilePath: "/static/logo.png",
				downloadedImage: ""
			}
		},
		methods: {
			updateImage() {
				uni.chooseImage({
					count: 6,
					sourceType: ['album'],
					success: (res) => {
						console.log("updateImage choose:" + res.tempFilePaths[0]);
						this.iconFilePath = res.tempFilePaths[0];
						uni.previewImage({
							urls: res.tempFilePaths,
						});
					}
				});
			},
			downloadNetImage() {
				const imgUrl = "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg";
				console.log("开始下载图片:", imgUrl);
				this.downloadedImage = "";
				const xhr = new XMLHttpRequest();
				xhr.open('GET', imgUrl, true);
				xhr.responseType = 'blob';

				xhr.addEventListener('progress', (event) => {
					if (event.lengthComputable) {
						const progress = Math.floor((event.loaded / event.total) * 100);
						console.log(`[${new Date().toLocaleTimeString()}] 下载进度：${progress}%`);
					}
				});

				xhr.onload = () => {
					if (xhr.status === 200) {
						const blob = new Blob([xhr.response]);
						this.downloadedImage = window.URL.createObjectURL(blob);
						console.log("图片下载成功，路径：", this.downloadedImage);
					} else {
						console.error("下载状态异常，状态码：", xhr.status);
						uni.showToast({
							title: "下载失败",
							icon: "none"
						});
					}
				};

				xhr.send();
			}
		}
	};
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 300rpx;
		width: 300rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
		border-radius: 500rpx;
	}
</style>